package com.internship.javawebinternship.myUtils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.URL;


public class GetLocation {

    public void location(HttpServletRequest request){
//        String IP = "113.13.21.184";
//        String baiduURL = "https://api.map.baidu.com/location/ip?ak=LRZCZkb95Y33uN8sKk9f80n4fg7UQu9s&ip=" + IP + "&coor=gcj02";
        HttpSession session = request.getSession(false);

        String gaodeURL = "https://restapi.amap.com/v3/geocode/geo?key=f21d1448dcde0c311b9b80f4886a0e43&address=";

        String URL = "https://ip.hao86.com/";
        String province = "";
        String city = "";
        String district = "";

        try {
            Document document = Jsoup.parse(new URL(URL), 10000);
            Elements need = document.getElementsByClass("ip_lay_table");

            String s = need.toString();
//            String IP = result.split("<td width=\"20%\">ip</td>\n {3}<td>")[1].split("<span")[0];
            String location = s.split("<td width=\"20%\">地理定位</td>\n {3}<td>")[1].split("</td>")[0];

//            System.out.println(location + "\n" + IP);

            gaodeURL = gaodeURL + location;

            Connection.Response response = Jsoup.connect(gaodeURL).timeout(10000).userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.56").ignoreContentType(true).execute();
            Document temp = response.parse();

            String main = temp.toString().split("<html>\n <head></head>\n <body>\n ")[1].split("\n </body>\n</html>")[0];

            main = UnicodeUtil.toString(main);

            province = main.split(",\"province\":\"")[1].split("\"")[0];
            city = main.split(",\"city\":\"")[1].split("\"")[0];
            district = main.split(",\"district\":\"")[1].split("\"")[0];


        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            System.out.println(province + " " + city + " " + district);
            session.setAttribute("province",province);
            session.setAttribute("city",city);
            session.setAttribute("district",district);
        }
    }

}

